package com.rcloud.server.sealtalk.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.rcloud.server.sealtalk.configuration.SealtalkConfig;
import com.rcloud.server.sealtalk.util.Json;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 *
 * Created by lgh on 2018/07/27.
 */
@Slf4j
@Service
public class AttachFileService {

    @Autowired
    private UploadManager uploadManager;

	@Autowired
	private SealtalkConfig config;

    @Autowired
    private Auth auth;

    public final static String NORM_MONTH_PATTERN = "yyyy/MM/dd/";

	@Transactional(rollbackFor = Exception.class)
	public String uploadFile(byte[] bytes, String originalName) throws QiniuException {
		String extName = FileUtil.extName(originalName);
		String fileName =DateUtil.format(new Date(), NORM_MONTH_PATTERN)+ IdUtil.simpleUUID() + "." + extName;
		String upToken = auth.uploadToken(config.getQiniuBucketName(),fileName);
	    Response response = uploadManager.put(bytes, fileName, upToken);
	    Json.parseObject(response.bodyString(),  DefaultPutRet.class);
		return fileName;
	}

}
